import { holdList } from '@/indexDB/initHold'
import { computed, ref } from 'vue'
import dayjs from 'dayjs'
import isToday from 'dayjs/plugin/isToday'
import { typeReqMap } from '@/views/hold/useLatestPrice'
import pLimit from 'p-limit'
import { assetsDB } from '@/indexDB'

import type { FundData } from '@/api/stock'
import type { HoldType } from '@/views/hold/model'
import type { StockHistory } from '@/indexDB/initStock'

dayjs.extend(isToday)

const limitReq = pLimit(6)

const OUT_TYPE: HoldType[] = ['fund-out', 'currency']

const innerStockList = computed(() => {
  return holdList.value.filter(each => each.code && !OUT_TYPE.includes(each.type))
})

const outStockList = computed(() => {
  return holdList.value.filter(each => each.code && OUT_TYPE.includes(each.type))
})

const LAST_OUT_TASK_TIME = 'LAST_OUT_TASK_TIME'
const lastOutTaskTime = ref(localStorage.getItem(LAST_OUT_TASK_TIME))

export const updateOutStock = async () => {
  console.log('开始更新场外数据');
  const resList = await Promise.all(outStockList.value.map(each => {
    const { type, code } = each
    const req = typeReqMap[type]
    return limitReq(() => req([code!]))
  }))

  const stockHistoryList = resList.map(stock => {
    const { A, B, C, D, code } = stock as FundData
    const nowPrice = B.value as number
    const risePercent = D.value as number
    const lastPrice = +(nowPrice / (1 + risePercent)).toFixed(4)
    const totalPrice = C.value as number
    const data: StockHistory = {
      code,
      nowPrice,
      lastPrice,
      risePercent,
      totalPrice,
      type: 'fund',
      updateTime: +new Date(A.value)
    }

    return data
  })

  await assetsDB.stockHistoryList.bulkAdd(stockHistoryList)

  localStorage.setItem(LAST_OUT_TASK_TIME, +new Date() + '')

  console.log('场外数据更新完成');
}


export const useStock = () => {

  const outTask = async () => {
    if (!lastOutTaskTime.value || !dayjs(+lastOutTaskTime.value).isToday()) {
      // 场外任务没跑过，就跑一次
      updateOutStock()
    }
  }

  // outTask()

  return {
    outTask
  }
}